<?php

class PJobpositionHelper
{
   //skill level
   const SKILL_LEVEL_KNOW = 1;  //了解
   const SKILL_LEVEL_GENERALE = 2; //普通
   const SKILL_LEVEL_SKILLED = 3;  //熟练
   const SKILL_LEVEL_PROFICIENTE = 4;  //精通

   //get publish_date or applied_num sort info
   public static function getListOrder() {
      $app = PFactory::getApplication();
      $jobpositiondir = $app->getUserState('jobpositiondir', null);
      $orderby = JArrayHelper::getValue($jobpositiondir, 'orderby', 'renew');
      $orderdir = strtoupper(JArrayHelper::getValue($jobpositiondir, 'orderdir', 'desc'));     
      $listorders = "";   
      $listorders=$orderby." ".$orderdir;
      return $listorders;
   }
   
   public static function checkboxList($data, $name,$attribs = null, $optKey = 'value', $optText = 'text', $selected = null,$id="all",$class="", $idtag = false,$translate = false) {
      reset($data);
      if(is_array($attribs)){
         $attribs = JArrayHelper::toString($attribs);
      }
      $id_text = $idtag ? $idtag : $name;
      $html = '';
      $n=count($data);
      $i=1;
      $html.='<li id='.$id.' class="jobposition_search_link '.$class.'" style="padding-left:0px;"><span>全部</span></li>';
      $html.='<li class="line" style="margin-left:0px;">|</li>';
      foreach($data as $obj){
         $i++;
         $k = $obj->$optKey;
         $t = $translate ? JText::_($obj->$optText) : $obj->$optText;
         $id = (isset($obj->id) ? $obj->id : null);
         $extra = '';
         $extra .= $id ? ' id="' . $obj->id . '"' : '';
         if(is_array($selected)){
            foreach($selected as $val){
               $k2 = is_object($val) ? $val->$optKey : $val;
               if($k == $k2){
                  $extra .= ' checked="checked"';
                  break;
               }
            }
         }else{
            $extra .= ((string) $k == (string) $selected ? ' checked="checked"' : '');
         }
         $html .= "\n\t" . "\n\t" . '<li><input type="checkbox" name="' . $name . '"' . ' id="' . $id_text .'_'. $k . '" value="' . $k . '"' . ' ' . $extra . ' '. $attribs . '><label style="font-weight:normal;text-align:left;width:auto;" for="' . $id_text .'_'. $k . '">' . $t .'</label></li>';
         if($i<=$n){
            $html .= "\n\t" . "\n\t" .'<li class="line">|</li>';
         }
      }
      $html .= "\n";
      return $html;
   }
   
   public static function getSelectOptionArray($array){
      if(empty($array))
         return;
      $new_array=array();
      foreach($array as $key =>$item){
        // we have positions which dodesn't id_cit/state
         if(!empty($item))
            $new_array[]=JHTML::_('select.option',  $key, JText::_( $item ));
      }
      return $new_array;
   }

   public static function getPosTxt($positions) {
      $positions = array_filter($positions);
      if (empty($positions))
         return '';

      function filter($v){
         if($v == '其它' || $v == '其他')
            return false;
         return true;
      }

      $pos = array_filter(array_reverse($positions), 'filter');
      return empty($pos) ? '其他' : array_pop($pos);
   }
   
   public static function getSavedFolderID($uid = "") {
      if(empty($uid)) {
         $uid = OC_User::getUser();
      }
   
      $db = PFactory::getDbo();
      $db->stayOnMaster();
      $query = "SELECT folder_id FROM *PREFIX*hr_job_folder WHERE folder_name='我的收藏' AND system=1 AND owner=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $saveFolderID = $db->loadResult();
      if (!$saveFolderID) {
         // create saved folder
         $query = "INSERT INTO *PREFIX*hr_job_folder (folder_name, owner, system) VALUES ('我的收藏', " . $db->quote($uid) . ", 1)";
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $db->leaveOnMaster();
            return false;
         }
         $query = 'SELECT LAST_INSERT_ID()';
         $db->setQuery($query);
         $saveFolderID = $db->loadResult();
         CacheHelper::triggerRemove($uid, array('*PREFIX*hr_job_folder'));
      }
   
      $db->leaveOnMaster();
      return $saveFolderID;
   }
   
   public static function getSettopFolderID($uid = "") {
      if(empty($uid)) {
         $uid = OC_User::getUser();
      }
       
      $db = PFactory::getDbo();
      $db->stayOnMaster();
      $query = "SELECT folder_id FROM *PREFIX*hr_job_folder WHERE folder_name='置顶' AND system=1 AND owner=" . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $saveFolderID = $db->loadResult();
      if (!$saveFolderID) {
         // create saved folder
         $query = "INSERT INTO *PREFIX*hr_job_folder (folder_name, owner, system) VALUES ('置顶', " . $db->quote($uid) . ", 1)";
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $db->leaveOnMaster();
            return false;
         }
         $query = 'SELECT LAST_INSERT_ID()';
         $db->setQuery($query);
         $saveFolderID = $db->loadResult();
         CacheHelper::triggerRemove($uid, array('*PREFIX*hr_job_folder'));
      }
       
      $db->leaveOnMaster();
      return $saveFolderID;
   }
   
   public static function getDirInfo($fid = 0, $uid = '') {
      if (empty($fid))
         return null;
   
      if(empty($uid)) {
         $uid = OC_User::getUser();
      }
   
      $db = PFactory::getDbo();
      // join delaytask to see if the fid is auto-created subfolder name based on task 
      $query = "SELECT f.folder_id AS id,f.num, IF(d.summary IS NOT NULL, d.summary, f.folder_name) AS foldername, type, data " .          
               " FROM *PREFIX*hr_job_folder AS f " .
               " LEFT JOIN #__delaytasks AS d ON CONCAT('_t', d.id) = f.folder_name" . 
               " WHERE f.owner=" . $db->quote($uid) . " AND f.folder_id=" . intval($fid);

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssoc();
   }

   public static function getJobGroupData($fid = 0, $uid = '') {
      if (empty($fid))
         return null;
   
      if(empty($uid)) {
         $uid = OC_User::getUser();
      }
   
      $db = PFactory::getDbo();
      $query = "SELECT hjff.job_id, jj.job_title FROM *PREFIX*hr_job_folder_files AS hjff " .
               " LEFT JOIN *PREFIX*hr_job_folder AS hjf ON hjf.folder_id=hjff.folder_id " .
               " LEFT JOIN #__jobs_job AS jj ON jj.id=hjff.job_id " .
               " WHERE jj.is_active='y' AND jj.is_trashed=0 AND hjf.owner=" . $db->quote(OC_User::getUser()) . " AND hjff.folder_id=" . intval($fid);

      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList('job_id', 'job_title');
   }
   
   public static function getCustomFolderList($uid = '', $limit = 0, $type = 'user', $full = false) {
      if(empty($uid)) {
         $uid = OC_User::getUser();
      }
   
      $db = PFactory::getDbo();
      if ($type == 'user') {
         if ($full) {
            $query = "SELECT folder_id, folder_name, num FROM *PREFIX*hr_job_folder WHERE (system=0 OR folder_name='我的收藏') AND owner=" . $db->quote($uid) . " AND type='user'
                      ORDER BY CASE WHEN folder_name='我的收藏' THEN 0
                               ELSE 1
                               END, folder_id ASC";
         } else {
            $query = "SELECT folder_id, folder_name, num FROM *PREFIX*hr_job_folder WHERE system=0 AND owner=" . $db->quote($uid) . " AND type='user' ORDER BY folder_id ASC";
         }
      } else {
         if ($full) {
            $query = "SELECT folder_id, folder_name, num FROM *PREFIX*hr_job_folder WHERE system=0 AND owner=" . $db->quote($uid) . " AND type=" . $db->quote($type) . "
                      ORDER BY folder_id ASC";
         } else {
            $query = "SELECT folder_id, folder_name, num FROM *PREFIX*hr_job_folder WHERE system=0 AND owner=" . $db->quote($uid) . " AND type=" . $db->quote($type) . " ORDER BY folder_id ASC";
         }
      }
   
      if ($limit) {
         $query .= ' LIMIT ' . $limit;
      }
   
      /* disable cache because it's not stable for now
      $cache = CacheHelper::getCache('app_jobposition');
      $data = $cache->call(array('PJobpositionHelper', '_getCustomFolderList'), $query);
      CacheHelper::setTriggers($uid, $cache, array('*PREFIX*hr_job_folder'));
      */
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }
    
   public static function _getCustomFolderList($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }
   
   // build search url, which carry original url params
   public static function getSearchUrl() {
      $JURI = JURI::getInstance();
      $curPath  = $JURI->toString(array('path'));
      if ($curPath == OC_Helper::linkToRoute('jobpos_search')) {
         $searchUrl = $JURI->toString(array('path','query'));
      } else {
         $curQuery = $JURI->toString(array('query'));
         $searchUrl = OC_Helper::linkToRoute('jobpos_search') . $curQuery;
      }
   
      return $searchUrl;
   }

  /**
    * get group jobs_id
    */
   public static function getGroupsJobsId($jobid) {
      if(empty($jobid))
         return null;
      $db = PFactory::getDbo();
      $query = "SELECT id FROM #__jobs_job WHERE group_id = " .intval($jobid). " OR id = " .intval($jobid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList();
   }

   public static function checkJobpositionDetail($jobid=0,&$error='') {
      if (empty($jobid)) {
         $error = "您无权访问该资源！";
         return false;
      }

      // Define a error msg array
      $keynames = array(
         'job_title' => '职位名称',
         'id_pos_type' => '职能类别',
         'id_salary_type' => '月薪',
         'long_desc' => '职位描述'
      );

      $db = PFactory::getDbo();
      $query = "SELECT job_title,id_pos_type,id_salary_type,long_desc,is_trashed FROM #__jobs_job WHERE id = ".intval($jobid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $result = $db->loadAssoc();

      if (!empty($result['is_trashed'])) {
         $error = "该职位已加入回收站，无法推送";
         return false;
      }
      unset($result['is_trashed']);

      $missing_fields = array();
      foreach ($result as $k => $v) {
         if (empty($v)) {
            array_push($missing_fields, '<b>'.$keynames[$k].'</b>');
         }
      }

      if (!empty($missing_fields)) {
         $error = "推送失败, 请您完善以下信息后再试: " . implode(',', $missing_fields);
         return false;
      }

      return true;
   }

   public static function getJobMatchFl($fl,$level){
      $db = JFactory::getDbo();
      $flinfo = array();
      $query = "SELECT a.id FROM oc_hr_interview_questions AS a
                LEFT JOIN jos_jobs_fl AS b ON b.name = a.text_hr WHERE a.alias='LANG' AND b.id=".intval($fl);
      $db->setQuery($query);
      $flinfo['fl'] = $db->loadResult();
      if(empty($flinfo['fl'])){
         $flinfo['flevel'] ='';
      }else{
         if(in_array($level, array('1','2','3'))){
            $flinfo['flevel']=1;
         }elseif($level == 4){
            $flinfo['flevel'] = 2;
         }elseif($level == 5){
            $flinfo['flevel'] = 3;
         }
      }
      return $flinfo;
   }

}
